package com.taomus.mytools.lang.jython;

import org.python.core.PyJavaType;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomus.mytools.lang.inter.IInvoke;
import com.taomus.mytools.lang.inter.IMethod;

public class JythonMethod implements IMethod {
	
	private PythonInterpreter pi;
	
	public JythonMethod(PythonInterpreter pi){
		this.pi = pi;
	}

	@Override
	public IInvoke getMethod(String name) {
		PyObject po = pi.get("pyinstance");
		return new JythonInvoke(po,name);
	}
	
	public static class JythonInvoke implements IInvoke{
		private static Logger logger = LoggerFactory.getLogger(IInvoke.class);
		private PyObject po;
		private String name;
		
		public JythonInvoke(PyObject po,String name) {
			super();
			this.po = po;
			this.name = name;
		}

		
		@Override
		public Object invoke() {
			logger.debug("invoke "+this.name);
			return po.invoke(this.name).__tojava__(Object.class);
		}

		@Override
		public Object invoke(Object... args) {
			logger.debug("invoke "+this.name);
			if(args == null){
				PyObject[] pyArgs = null;
				return po.invoke(this.name, pyArgs);
			}
			PyObject[] pyArgs = this.objToPyObj(args);
			return po.invoke(this.name, pyArgs).__tojava__(Object.class);
		}
		
		private PyObject[] objToPyObj(Object ...args){
			int len = args.length;
			PyObject[] pyos = new PyObject[len];
			for(int i=0;i<len;i++){
				pyos[i] = toPyType(args[i]);
			}
			return pyos;
		}
		
		
		private PyObject toPyType(Object arg){
			return PyJavaType.wrapJavaObject(arg); 
		}
		
	}
	
}
